﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using SmallERP.COM;
using SmallERP.MODEL.FoundationModel;
using System.Diagnostics;
using SmallERP.PinBan.PB.Presenter;
using SmallERP.PinBan;
using System.Net;
using System.Text.RegularExpressions;

namespace Small.PinBan
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                LayoutDll.ClassInterFace InterFace = new LayoutDll.ClassInterFace();

            }
            catch (Exception ex)
            {
                MessageBox.Show("软件未授权请联系上海惟鸿网络", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //MessageBox.Show(ex.ToString());
                Environment.Exit(1);
            }



            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-CN");
            bool isAppRunning = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex(
                false,
                System.Diagnostics.Process.GetCurrentProcess().ProcessName,
                out isAppRunning);

            if (!isAppRunning)
            {
                MessageBox.Show("本程序已运行，请不要重复运行！");
                return;
            }
            else
            {

                if (DealResult())
                {
                    Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                    Application.EnableVisualStyles();


                    Application.Run(new FrmMain_PinBan());
                }
            }
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            //throw new NotImplementedException();
            //发生了没有捕获的线程异常 
            WriteLogForCheck.WriteLogFile("发生了未捕获的线程异常:" + e.Exception.Message + "代码：" + e.Exception.Source);
        }

        #region 公共的
        private static StartUPUtil _upBLL;
        private static bool isDoing = false;
        static void t_Tick(object sender)
        {
            if (!isDoing)
            {
                isDoing = true;
                if (_upBLL == null)
                {
                    _upBLL = new StartUPUtil();
                }
                //StartUPUtil upBLL = new StartUPUtil();
                ServerInfo serverInfo = new ServerInfo();
                string errMsg = string.Empty;
                int result = _upBLL.GetServerInfo(out serverInfo, out errMsg);
                if (result != 0)
                {
                    MessageBox.Show("启动生成图片失败，请手动启动生成图片");
                    Environment.Exit(0);
                }
                isDoing = false;
            }
        }

        private static bool DealResult()
        {
            if (_upBLL == null)
            {
                _upBLL = new StartUPUtil();
            }
            //StartUPUtil upBLL = new StartUPUtil();
            //ServerInfo serverInfo = new ServerInfo();
            //string errMsg = string.Empty;
            //int result = _upBLL.GetServerInfo(out serverInfo, out errMsg);
            //if (result != 0)//有问题
            //{
            //    MessageBox.Show(errMsg);

            //    if (result == -6)
            //    {
            //        Application.ApplicationExit += new EventHandler(Restart);
            //    }

            //    Application.Exit();
            //    return false;
            //}



            //DataTransfer.Port = serverInfo.ServerTCPPort;
            //DataTransfer.Addr = serverInfo.ServerIP;
            string ip = _upBLL.GetIpAdress();
            // string ip = "";
            string computerName;
            IPAddress[] ipAddress;
            computerName = Dns.GetHostName();
            ipAddress = Dns.GetHostAddresses(computerName);

            string strIP = "";
            foreach (IPAddress aip in ipAddress)
            {
                if (Regex.IsMatch(aip.ToString(), @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase))
                {
                    strIP = aip.ToString();
                    break;
                }

            }
            if (string.IsNullOrEmpty(strIP))
            {
                strIP = "127.0.0.1";
            }
            ip = strIP;
            if (string.IsNullOrEmpty(ip))
            {
                FrmAdress frmad = new FrmAdress();
                if (DialogResult.OK == frmad.ShowDialog())
                {
                    ip = frmad.IP;

                }
                frmad.Close();
            }
            DataTransfer.IPadress = ip;
            int modefy = MondifyConfig.Modify(Application.ExecutablePath, ip);
            if (modefy == 0)
            {
                //MessageBox.Show("生成图片地址已改变，请重新启动拼版");
                //Environment.Exit(1);                                                                        //return false;
                Application.Restart();
                return false;
            }
            bool isHostRun = false;

            Process[] temp = Process.GetProcessesByName("SmallERP.Host");
            if (temp.Length > 0)
            {
                isHostRun = true;
            }
             isHostRun = true;
            if (isHostRun)
            {
                return true;
            }
            else
            {
                try
                {
                    System.Diagnostics.Process.Start(Application.StartupPath + "\\SmallERP.Host.exe");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                //MessageBox.Show("请先启动生成图片!!");
                //Environment.Exit(1);
                Application.Restart();
                return false;
            }

        }

        private static void Restart(object sender, EventArgs e)
        {
            Process.Start(Application.ExecutablePath);
        }


        #endregion
    }
}
